package com.situ.mall.service.impl;

import com.situ.mall.mapper.CartMapper;
import com.situ.mall.mapper.OrderItemMapper;
import com.situ.mall.mapper.OrderMapper;
import com.situ.mall.pojo.Order;
import com.situ.mall.pojo.OrderItem;
import com.situ.mall.pojo.vo.CartVO;
import com.situ.mall.pojo.vo.OrderVO;
import com.situ.mall.service.ICartService;
import com.situ.mall.service.IOrderService;
import com.situ.mall.util.JSONResult;
import com.situ.mall.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private SnowFlake snowFlake;
    @Autowired
    private ICartService cartService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public JSONResult add(Order order) {
        //现在order对象里面已经有的信息： userId、shippingId、paymentType
        //使用雪花算法生成订单的订单号
        long id = snowFlake.nextId();
        order.setOrderNo(id);
        //订单状态:0-已取消-10-未付款，20-已付款，40-已发货，50-交易成功，60-交易关闭
        order.setStatus(10);

        //购物车里面选中要去结算的商品
        List<CartVO> cartVOList = cartService.selectByUserIdAndChecked(order.getUserId());
        //记录整个订单的总金额
        BigDecimal payment = BigDecimal.valueOf(0.0);
        for (CartVO cartVO : cartVOList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNo(id);
            orderItem.setUserId(order.getUserId());
            orderItem.setProductId(cartVO.getProductId());
            orderItem.setProductImage(cartVO.getProductImage());
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setCurrentUnitPrice(cartVO.getProductPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            //totalPricec=商品价格*数量
            BigDecimal productPrice = cartVO.getProductPrice();
            BigDecimal quantity = BigDecimal.valueOf(cartVO.getQuantity());
            BigDecimal totalPrice = productPrice.multiply(quantity);
            orderItem.setTotalPrice(totalPrice);
            orderItemMapper.insert(orderItem);
            //每次生成订单项的时候，应该去购物车里面把对应的购物车信息删除掉
            cartMapper.deleteByPrimaryKey(cartVO.getId());

            payment = payment.add(totalPrice);
        }

        order.setPayment(payment);
        orderMapper.insert(order);

        return JSONResult.ok();
    }

    @Override
    public List<OrderVO> selectByUserId(Integer id) {
        return orderMapper.selectByUserId(id);
    }


    public static void main(String[] args) {
        System.out.println(0.1+0.2);
    }
}
